<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 卡片头部保留 -->
      <div class="card-header">
        <h2>📋 账单管理</h2>
        <el-button type="primary" @click="showAddDrawer = true">添加账单</el-button>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeName">
        <!-- 第一个标签页：经营记账 -->
        <el-tab-pane label="账单列表" name="account">
          <!-- 搜索和筛选区域 -->
          <div class="search-filter-container">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="记账日期" style="width: 250px;">
                <el-date-picker v-model="searchForm.record_date" type="datetime" placeholder="年/月/日" format="YYYY-MM-DD"
                  date-format="MMM DD, YYYY" time-format="HH:mm" />
              </el-form-item>
              <el-form-item label="所属月份" style="width: 250px;">
                <el-date-picker v-model="searchForm.accounting_month" type="datetime" placeholder="年/月" format="YYYY-MM"
                  date-format="MMM DD, YYYY" time-format="HH:mm" />
              </el-form-item>
              <el-form-item label="分类">
                <el-select v-model="searchForm.category" placeholder="全部" style="width: 170px">
                  <el-option label="全部" value="" />
                  <el-option label="食堂收入" value="canteen_income" />
                  <el-option label="补贴" value="subsidy" />
                  <el-option label="原料" value="ingredients" />
                  <el-option label="工资" value="salary" />
                  <el-option label="物流" value="logistics" />
                  <el-option label="公用事业费" value="utilities" />
                  <el-option label="设备更换" value="equipment_replacement" />
                  <el-option label="其他费用" value="other_expenses" />
                  <el-option label="租金" value="rent" />
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="全部" style="width: 170px">
                  <el-option label="全部" value="" />
                  <el-option label="收入" value="income" />
                  <el-option label="支出" value="expense" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 统计卡片区域 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">总收入</div>
                <div class="stat-value">¥{{ stats.totalIncome.toFixed(2) }}</div>
                <div class="stat-trend" :class="stats.incomeGrowth >= 0 ? 'text-success' : 'text-danger'">
                  {{ stats.incomeGrowth >= 0 ? '+' : '' }}{{ stats.incomeGrowth }}%
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">总支出</div>
                <div class="stat-value">¥{{ stats.totalExpense.toFixed(2) }}</div>
                <div class="stat-trend" :class="stats.expenseGrowth >= 0 ? 'text-danger' : 'text-success'">
                  {{ stats.expenseGrowth >= 0 ? '+' : '' }}{{ stats.expenseGrowth }}%
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">净利润</div>
                <div class="stat-value">¥{{ stats.netProfit.toFixed(2) }}</div>
                <div class="stat-trend" :class="stats.netProfit >= 0 ? 'text-success' : 'text-danger'">
                  {{ stats.netProfit >= 0 ? '盈利' : '亏损' }}
                </div>
              </el-card>
            </el-col>
            <!-- 第四个卡片可以根据实际需求展示其他统计数据 -->
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">交易笔数</div>
                <div class="stat-value">{{ tableData.length }} 笔</div>
                <div class="stat-trend">
                  {{tableData.filter(item => item.record_type === 'income').length}}收入/{{tableData.filter(item =>
                    item.record_type === 'expense').length}}支出
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 表格区域 -->
          <div class="table-container">
            <el-table :data="tableData" stripe style="width: 100%; margin-top: 16px" v-loading="loading">
              <el-table-column prop="id" label="序号" width="70" align="center" />
              <el-table-column prop="record_date" label="记账日期" width="150">
                <template #default="{ row }">
                  {{ dayjs(row.record_date).format('YYYY-MM-DD') }}
                </template>
              </el-table-column>
              <el-table-column prop="accounting_month" label="所属月份" width="120">
                <template #default="{ row }">
                  {{ dayjs(row.accounting_month).format('YYYY年MM月') }}
                </template>
              </el-table-column>
              <el-table-column prop="record_type" label="记账类型" width="150" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.record_type === 'income' ? 'success' : 'danger'" size="small">
                    {{ row.record_type === 'income' ? '收入' : '支出' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="accounting_item" label="收支项目" width="220" />
              <el-table-column prop="amount" label="金额" width="180" align="right">
                <template #default="{ row }">
                  <span :class="row.record_type === 'income' ? 'text-success' : 'text-danger'">
                    {{ row.record_type === 'income' ? '+' : '-' }}￥{{ row.amount }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="handler" label="经办人" width="100" align="center" />
              <el-table-column label="收据" width="100" align="center">
                <template #default="{ row }">
                  <el-link v-if="row.receipt_image_path" type="primary" :underline="false"
                    @click="previewReceipt(row.receipt_image_path)">查看</el-link>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" width="180" show-overflow-tooltip />
              <el-table-column label="操作" width="180" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button size="small" @click="handleEdit(row)">
                    <el-icon>
                      <Edit />
                    </el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" @click="handleView(row)">
                    <el-icon>
                      <View />
                    </el-icon>
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页区域 -->
          <div class="pagination-container">
            <div class="pagination-container">
              <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 30, 40]" layout="prev, pager, next, sizes, jumper, ->, total" background
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 第二个标签页：收支统计 -->
        <el-tab-pane label="收支统计" name="stats">
          <!-- 搜索栏区域 -->
          <div class="search-filter-container">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="记账日期">
                <el-date-picker v-model="searchForm.record_date" type="datetime" placeholder="年/月/日" format="YYYY-MM-DD"
                  date-format="MMM DD, YYYY" time-format="HH:mm" />
              </el-form-item>
              <el-form-item label="所属月份">
                <el-date-picker v-model="searchForm.accounting_month" type="datetime" placeholder="年/月/日"
                  format="YYYY-MM" date-format="MMM DD, YYYY" time-format="HH:mm" />
              </el-form-item>
              <el-form-item label="分类">
                <el-select v-model="searchForm.category" placeholder="全部" style="width: 300px">
                  <el-option label="全部" value="" />
                  <el-option label="食堂收入" value="canteen_income" />
                  <el-option label="补贴" value="subsidy" />
                  <el-option label="原料" value="ingredients" />
                  <el-option label="工资" value="salary" />
                  <el-option label="物流" value="logistics" />
                  <el-option label="公用事业费" value="utilities" />
                  <el-option label="设备更换" value="equipment_replacement" />
                  <el-option label="其他费用" value="other_expenses" />
                  <el-option label="租金" value="rent" />
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="全部" style="width: 300px">
                  <el-option label="全部" value="" />
                  <el-option label="收入" value="income" />
                  <el-option label="支出" value="expense" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 图表容器 -->
          <div class="chart-container">
            <div ref="chartRef" class="chart"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

    <!-- 添加抽屉组件 -->
  <el-drawer v-model="showAddDrawer" size="50%" direction="rtl">
    <template #header="{ titleId, titleClass }">
      <div class="drawer-header">
        <h4 :id="titleId" :class="titleClass" style="font-size: 20px; margin: 0;">添加账单</h4>
      </div>
    </template>

    <div class="drawer-content" style="position: absolute;top: 50px;left: 0px;">
      <!-- 表单区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px">
        <!-- 记账日期和所属月份 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记账日期" prop="record_date">
              <el-date-picker v-model="addForm.record_date" type="date" placeholder="选择记账日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属月份" prop="accounting_month">
              <el-date-picker v-model="addForm.accounting_month" type="month" placeholder="选择所属月份" format="YYYY-MM"
                value-format="YYYY-MM" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 记账类型和收支项目 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记账类型" prop="record_type">
              <el-select v-model="addForm.record_type" placeholder="请选择记账类型" style="width: 100%">
                <el-option label="收入" value="income" />
                <el-option label="支出" value="expense" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收支项目" prop="accounting_item">
              <el-select v-model="addForm.accounting_item" placeholder="请选择收支项目" style="width: 100%">
                <el-option label="食堂收入" value="canteen_income" />
                <el-option label="补贴" value="subsidy" />
                <el-option label="原料" value="ingredients" />
                <el-option label="工资" value="salary" />
                <el-option label="物流" value="logistics" />
                <el-option label="公用事业费" value="utilities" />
                <el-option label="设备更换" value="equipment_replacement" />
                <el-option label="其他费用" value="other_expenses" />
                <el-option label="租金" value="rent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 金额和经办人 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model.number="addForm.amount" placeholder="请输入金额" style="width: 100%">
                <template #suffix>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-input v-model="addForm.handler" placeholder="请输入经办人" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 关联单据 -->
        <el-form-item label="关联单据" prop="related_document">
          <el-input v-model="addForm.related_document" placeholder="请输入关联单据编号" style="width: 100%" />
        </el-form-item>

        <!-- 收据图片 -->
        <el-form-item label="收据图片" prop="receipt_image_path">
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
            accept=".jpg,.jpeg,.png,.gif,.bmp" v-model:file-list="addFileList" @change="handleAddFileChange"
            @remove="handleAddFileRemove">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <!-- 图片预览对话框 -->
          <el-dialog v-model="dialogVisible" width="600px">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>

          <div class="el-upload__tip">支持 jpg/png/gif/bmp 格式</div>

          <!-- 预览区域 -->
          <div v-if="addForm.receipt_image_path && addFileList.length === 0" class="preview-container">
            <img :src="addForm.receipt_image_path" alt="收据预览" class="preview-image" />
          </div>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" style="width: 100%" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="drawer-footer">
      <el-button @click="showAddDrawer = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="saveLoading">保存</el-button>
    </div>
  </el-drawer>


  <!-- 编辑抽屉 -->
  <el-drawer v-model="drawer" :show-close="false" size="50%" direction="rtl">
    <template #header>

      <div class="drawer-content" style="position: relative;bottom: 30px;right: 10px;">
        <h4 :id="titleId" :class="titleClass" style="font-size: 20px;">编辑账单</h4>
      <el-icon @click="drawer = false" style="position: absolute; top: 15px; right: 15px; cursor: pointer; color: #999;font-size: 20px;">
        <Close />
      </el-icon>
        <!-- 表单区域 -->
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">

          <!-- 基本信息标题 -->
          <div class="form-section-title">基本信息</div>

          <!-- 记账日期和所属月份-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="记账日期" prop="record_date">
                <el-date-picker v-model="form.record_date" type="datetime" placeholder="选择记账日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属月份" prop="accounting_month">
                <el-date-picker v-model="form.accounting_month" type="month" placeholder="选择所属月份" format="YYYY-MM"
                  value-format="YYYY-MM" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 记账类型和收支项目 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="记账类型" prop="record_type">
                <el-select v-model="form.record_type" placeholder="请选择记账类型" style="width: 100%">
                  <el-option label="收入" value="income" />
                  <el-option label="支出" value="expense" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收支项目" prop="accounting_item">
                <el-select v-model="form.accounting_item" placeholder="请选择收支项目" style="width: 100%">
                  <el-option label="食堂收入" value="canteen_income" />
                  <el-option label="补贴" value="subsidy" />
                  <el-option label="原料" value="ingredients" />
                  <el-option label="工资" value="salary" />
                  <el-option label="物流" value="logistics" />
                  <el-option label="公用事业费" value="utilities" />
                  <el-option label="设备更换" value="equipment_replacement" />
                  <el-option label="其他费用" value="other_expenses" />
                  <el-option label="租金" value="rent" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 金额和经办人-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="金额" prop="amount">
                <el-input v-model.number="form.amount" placeholder="请输入金额" style="width: 100%">
                  <template #prefix>
                    <i class="el-icon-money"></i>
                  </template>
                  <template #suffix>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人" prop="handler">
                <el-input v-model="form.handler" placeholder="请输入经办人姓名" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 关联单据 -->
          <el-form-item label="关联单据" prop="related_document">
            <el-input v-model="form.related_document" placeholder="请输入关联单据编号" style="width: 100%" />
          </el-form-item>

          <!-- 收据图片 -->
          <el-form-item label="收据图片" prop="receipt_image_path">
            <!-- 上传组件 -->
            <el-upload action="/common/upload" list-type="picture-card" :auto-upload="false" :limit="1"
              accept=".jpg,.jpeg,.png,.gif,.bmp" v-model:file-list="editFileList" @change="handleEditFileChange"
              @remove="handleEditFileRemove">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>

            <!-- 预览区域：当有图片URL且未上传新图片时显示 -->
            <!-- 简化条件判断，只要有路径就显示 -->
            <!-- <div v-if="form.receipt_image_path && form.receipt_image_path.trim() !== ''" class="preview-container">
              <img :src="form.receipt_image_path" alt="收据预览" class="preview-image" />
            </div> -->
          </el-form-item>
          <!-- 备注 -->
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" style="width: 100%" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 操作按钮 -->
      <div class="drawer-footer">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 查看抽屉 -->
  <el-drawer v-model="viewDrawer" :show-close="false" size="50%" direction="rtl">
    <template #header="{ titleId, titleClass }">

      <div class="drawer-content">
        <h4 :id="titleId" :class="titleClass" style="font-size: 20px;">查看账单</h4>
        <el-icon @click="viewDrawer = false"
          style="position: absolute; top: 15px; right: 15px; cursor: pointer; color: #999;font-size: 20px;">
          <Close />
        </el-icon>
        <!-- 表单区域 -->
        <el-form ref="viewFormRef" :model="viewForm" label-width="120px" disabled>

          <!-- 基本信息标题 -->
          <div class="form-section-title">基本信息</div>

          <!-- 记账日期和所属月份-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="记账日期" prop="record_date">
                <el-date-picker v-model="viewForm.record_date" type="datetime" placeholder="选择记账日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属月份" prop="accounting_month">
                <el-date-picker v-model="viewForm.accounting_month" type="month" placeholder="选择所属月份" format="YYYY年MM月"
                  value-format="YYYY-MM" style="width: 100%" />
              </el-form-item>
            </el-col>

          </el-row>

          <!-- 记账类型和收支项目 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="记账类型" prop="record_type">
                <el-select v-model="viewForm.record_type" placeholder="请选择记账类型" style="width: 100%">
                  <el-option label="收入" value="income" />
                  <el-option label="支出" value="expense" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收支项目" prop="accounting_item">
                <el-select v-model="viewForm.accounting_item" placeholder="请选择收支项目" style="width: 100%">
                  <el-option label="食堂收入" value="canteen_income" />
                  <el-option label="补贴" value="subsidy" />
                  <el-option label="原料" value="ingredients" />
                  <el-option label="工资" value="salary" />
                  <el-option label="物流" value="logistics" />
                  <el-option label="公用事业费" value="utilities" />
                  <el-option label="设备更换" value="equipment_replacement" />
                  <el-option label="其他费用" value="other_expenses" />
                  <el-option label="租金" value="rent" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 金额和经办人-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="金额" prop="amount">
                <el-input v-model.number="viewForm.amount" placeholder="请输入金额" style="width: 100%">
                  <template #prefix>
                    <i class="el-icon-money"></i>
                  </template>
                  <template #suffix>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人" prop="handler">
                <el-input v-model="viewForm.handler" placeholder="请输入经办人姓名" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 关联单据 -->
          <el-form-item label="关联单据" prop="related_document">
            <el-input v-model="viewForm.related_document" placeholder="请输入关联单据编号" style="width: 100%" />
          </el-form-item>

          <!-- 收据图片 -->
          <el-form-item label="收据图片" prop="receipt_image_path">
            <el-upload action="" list-type="picture-card" auto-upload="false" limit="1"
              accept=".jpg,.jpeg,.png,.gif,.bmp" v-model:file-list="viewFileList" :disabled="true">
              <el-icon v-if="viewFileList.length === 0">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="el-upload__tip">支持 jpg/png/gif/bmp 格式</div>
          </el-form-item>

          <!-- 备注 -->
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="viewForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" style="width: 100%" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { getBillList, addBill, updateBill, getUploadFile, uploadFile, deleteUploadFile } from '../../api/finance'
import * as echarts from 'echarts'


// ==================== 统计相关 ====================
// 统计数据
const stats = reactive({
  totalIncome: 0,        // 总收入
  totalExpense: 0,       // 总支出
  netProfit: 0,          // 净利润
  incomeGrowth: 0,       // 收入增长率(示例)
  expenseGrowth: 0       // 支出增长率(示例)
})

// 计算统计数据
const calculateStats = (list) => {
  // 初始化统计值
  let income = 0
  let expense = 0

  // 遍历列表计算总和
  list.forEach(item => {
    const amount = Number(item.amount) || 0
    if (item.record_type === 'income') {
      income += amount
    } else {
      expense += amount
    }
  })

  // 更新统计数据
  stats.totalIncome = income
  stats.totalExpense = expense
  stats.netProfit = income - expense

  // 这里可以根据实际需求计算增长率
  // 示例：简单使用与上一次的差值比例
  stats.incomeGrowth = calculateGrowth(income, stats.totalIncome)
  stats.expenseGrowth = calculateGrowth(expense, stats.totalExpense)
}

// 计算增长率辅助函数
const calculateGrowth = (current, previous) => {
  if (previous === 0) return current > 0 ? 100 : 0
  return ((current - previous) / previous * 100).toFixed(1)
}

// ==================== 列表相关 ====================
/* -------- 搜索表单 -------- */
const searchForm = reactive({
  record_date: '',
  accounting_month: '',
  category: '',
  status: '',
})

/* -------- 表格 & 分页 -------- */
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

/* -------- 获取数据 -------- */
const fetchData = async (withFilter = true) => {
  loading.value = true
  try {
    const base = {
      page: currentPage.value,
      pagesize: pageSize.value
    }

    const params = { ...base }

    if (withFilter) {
      // 处理记账日期
      if (searchForm.record_date) {
        params.record_date = dayjs(searchForm.record_date).format('YYYY-MM-DD')
      }

      // 处理所属月份
      if (searchForm.accounting_month) {
        params.accounting_month = dayjs(searchForm.accounting_month).format('YYYY-MM')
      }

      // 处理分类
      if (searchForm.category) {
        params.accounting_item = searchForm.category
      }

      // 处理状态
      if (searchForm.status) {
        params.record_type = searchForm.status
      }
    }

    const { data } = await getBillList(params)
    tableData.value = data.rows || []
    total.value = data.total || 0

    // 计算统计数据
    calculateStats(tableData.value)
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

/* -------- 分页事件 -------- */
const handleSizeChange = val => { pageSize.value = val; fetchData(true) }
const handleCurrentChange = val => { currentPage.value = val; fetchData(true) }

/* -------- 搜索 & 重置 -------- */
const onSearch = () => { currentPage.value = 1; fetchData(true) }
const onReset = () => {
  Object.assign(searchForm, {
    record_date: '',
    accounting_month: '',
    category: '',
    status: '',
    remarks: ''
  })
  onSearch()
}

/* -------- 编辑 / 查看 -------- */
const handleEdit = async (row) => {
  // 重置表单和文件列表
  editFileList.value = [];
  form.receipt_image_path = '';

  // 复制行数据到表单
  Object.assign(form, {
    id: row.id,
    record_date: row.record_date,
    accounting_month: row.accounting_month,
    record_type: row.record_type,
    accounting_item: row.accounting_item,
    amount: row.amount,
    handler: row.handler,
    related_document: row.related_document,
    receipt_image_path: row.receipt_image_path || '', // 无图片时设为空字符串
    remarks: row.remarks
  });

  //仅当 receipt_image_path 存在且非空时，才加载图片
  if (form.receipt_image_path && form.receipt_image_path.trim() !== '') {
    try {
      const { data } = await getUploadFile({
        fileName: form.receipt_image_path.split('/').pop(),
        dirType: 3 // 经营记账分类
      });

      if (data && data.url) {
        const imageUrl = data.url.replace('/public', '/static');
        form.receipt_image_path = imageUrl;
        // 更新文件列表（用于上传组件的预览）
        editFileList.value = [{
          name: imageUrl.split('/').pop(), // 提取文件名
          url: imageUrl, // 绑定完整URL
          status: 'success' // 标记为成功状态
        }];
      } else {
        // 无图片时清空
        form.receipt_image_path = '';
        editFileList.value = [];
      }
    } catch (error) {
      console.error('获取图片地址失败:', error);
      // 仅在有图片路径但加载失败时提示，无路径时不提示
      ElMessage.error('图片加载失败');
    }
  }
  // 无图片时不执行任何加载逻辑，也不提示错误
  drawer.value = true;
};
/* -------- 收据预览 -------- */
const previewReceipt = (url) => window.open(url)

/* -------- 首次加载 -------- */
onMounted(() => fetchData(false))

// ==================== 添加相关 ====================
/* -------- 添加账单抽屉 -------- */
const showAddDrawer = ref(false)
const activeName = ref('account')
const addFileList = ref([]) // 添加文件列表
const dialogVisible = ref(false) // 图片预览对话框
const dialogImageUrl = ref('') // 图片预览URL

const addForm = reactive({
  record_date: '',
  accounting_month: '',
  record_type: 'income',
  accounting_item: '',
  amount: '',
  handler: '',
  related_document: '',
  receipt_image_path: '',
  remarks: ''
})

// 处理添加时文件选择
const handleAddFileChange = (file, fileList) => {
  addFileList.value = fileList
}

// 处理添加时文件移除
const handleAddFileRemove = (file, fileList) => {
  addFileList.value = fileList
  // 确保表单中的图片路径也被清除
  addForm.receipt_image_path = ''
}

const fileList = ref([])

// 关闭抽屉前的确认
const handleClose = () => {
  if (addForm.record_date || addForm.accounting_month || addForm.record_type !== 'income' || addForm.accounting_item || addForm.amount || addForm.handler || addForm.remarks) {
    ElMessageBox.confirm('您有未保存的数据，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      showAddDrawer.value = false
    }).catch(() => {
      // 用户点击了取消，不关闭抽屉
    })
  } else {
    showAddDrawer.value = false
  }
}
// 校验规则
const addFormRules = {
  record_date: [{ required: true, message: '请填写记账日期', trigger: 'blur' }],
  accounting_month: [{ required: true, message: '请填写所属月份', trigger: 'blur' }],
  record_type: [{ required: true, message: '请选择记账类型', trigger: 'change' }],
  accounting_item: [{ required: true, message: '请选择收支项目', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', message: '金额必须为数字', trigger: 'blur' }
  ],
  handler: [{ required: true, message: '请输入经办人', trigger: 'blur' }]
}


const addFormRef = ref(null)
const submitForm = async () => {
  await addFormRef.value.validate()

  saveLoading.value = true
  try {
    // 处理文件上传
    let receiptImagePath = ''
    if (addFileList.value.length > 0) {
      const formData = new FormData()
      formData.append('pic', addFileList.value[0].raw)
      formData.append('dirType', 3) // 经营记账分类

      try {
        const uploadRes = await uploadFile(formData)
        if (uploadRes.code === 0) {
          receiptImagePath = uploadRes.file.path
        } else {
          ElMessage.error(uploadRes.msg || '图片上传失败')
          return
        }
      } catch (error) {
        ElMessage.error('图片上传失败: ' + error.message)
        return
      }
    }

    // 构建提交数据
    const payload = {
      ...addForm,
      receipt_image_path: receiptImagePath
    }

    const res = await addBill(payload)
    if (res.code === 0) {
      ElMessage.success('添加成功')
      showAddDrawer.value = false
      fetchData(true)
      addFormRef.value.resetFields()
      addFileList.value = []
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message)
  } finally {
    saveLoading.value = false
  }
}

// ==================== 编辑相关 ====================
// 抽屉开关
const drawer = ref(false)
const saveLoading = ref(false)
const formRef = ref()
const editFileList = ref([])

// 编辑表单数据
const form = reactive({
  id: '',
  record_date: '',
  accounting_month: '',
  record_type: 'income',
  accounting_item: '',
  amount: '',
  handler: '',
  related_document: '',
  receipt_image_path: '',
  remarks: ''
})

// 编辑表单校验规则
const rules = {
  record_date: [{ required: true, message: '请填写记账日期', trigger: 'blur' }],
  accounting_month: [{ required: true, message: '请填写所属月份', trigger: 'blur' }],
  record_type: [{ required: true, message: '请选择记账类型', trigger: 'change' }],
  accounting_item: [{ required: true, message: '请选择收支项目', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入金额'));
          return;
        }

        const regex = /^(\d+)(\.\d{1,2})?$/;

        if (!regex.test(value)) {
          callback(new Error('金额格式不正确，最多支持两位小数'));
          return;
        }

        // 验证数值是否为正数
        const numValue = parseFloat(value);
        if (numValue <= 0) {
          callback(new Error('金额必须大于0'));
          return;
        }

        callback();
      },
      trigger: 'blur'
    }
  ],
  handler: [{ required: true, message: '请输入经办人', trigger: 'blur' }]
}

// 编辑抽屉关闭前的确认
const handleEditClose = () => {
  if (form.record_date || form.accounting_month || form.record_type !== 'income' || form.accounting_item || form.amount || form.handler || form.remarks) {
    ElMessageBox.confirm('您有未保存的数据，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      drawer.value = false
    }).catch(() => {
      // 用户点击了取消，不关闭抽屉
    })
  } else {
    drawer.value = false
  }
}

// 处理编辑时文件选择
const handleEditFileChange = async (file, fileList) => {
  editFileList.value = fileList;

  // 若选择了新图片，且之前有旧图，先调用删除接口清理旧图
  if (fileList.length > 0 && form.receipt_image_path) {
    try {
      const fileName = form.receipt_image_path.split('/').pop();
      await deleteUploadFile({ fileName, dirType: 3 });
      console.log('旧图片已自动删除');
    } catch (error) {
      console.warn('清理旧图片失败，不影响新图片上传:', error);
    }
    // 清空旧图路径，避免提交时冲突
    form.receipt_image_path = '';
  }
};
// 处理编辑时的文件删除
const handleEditFileRemove = async (file, fileList) => {
  //  清空表单中的图片路径
  form.receipt_image_path = '';
  // 更新文件列表
  editFileList.value = fileList;

  //  调用删除接口
  if (file.url) {
    try {
      // 从图片URL中提取后端存储的文件名
      const fileName = file.url.split('/').pop();
      // 调用删除接口
      const res = await deleteUploadFile({
        fileName: fileName,
        dirType: 3
      });
      if (res.code === 0) {
        ElMessage.success('图片删除成功');
      } else {
        ElMessage.error(res.msg || '图片删除失败');
      }
    } catch (error) {
      console.error('删除图片接口调用失败:', error);
      ElMessage.error('删除图片失败，请重试');
    }
  }
};
// 提交编辑表单
const submit = async () => {
  if (saveLoading.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true;
      try {
        let receiptImagePath = '';

        // 关键：只要有新选择的文件（无论是否有旧图），就上传
        if (editFileList.value.length > 0 && editFileList.value[0].raw) {
          const formData = new FormData();
          formData.append('pic', editFileList.value[0].raw);
          formData.append('dirType', 3);

          const uploadRes = await uploadFile(formData);
          console.log('上传成功，返回数据:', uploadRes);
          if (uploadRes.code === 0) {
            // 确保获取到正确的文件路径
            if (uploadRes.data && uploadRes.data.file_path) {
              console.log('准备设置文件路径:', receiptImagePath);
              receiptImagePath = uploadRes.data.file_path;
            } else {
              ElMessage.error('上传成功但未返回文件路径，请联系管理员');
              return;
            }
            // 更新文件列表状态
            editFileList.value = [{
              name: editFileList.value[0].name,
              url: receiptImagePath,
              status: 'success'
            }];
          } else {
            ElMessage.error(uploadRes.msg || '图片上传失败');
            return;
          }
        }

        // 提交表单（包含新图片路径）
        const payload = {
          ...form,

          receipt_image_path: receiptImagePath // 确保路径不为undefined
        };
        const res = await updateBill(form.id, payload);
        if (res.code === 0) {
          ElMessage.success('更新成功');
          drawer.value = false;
          fetchData(true);
          editFileList.value = []; // 清空列表，避免下次打开残留
        } else {
          ElMessage.error(res.msg || '更新失败');
        }
      } catch (err) {
        ElMessage.error('更新失败：' + err.message);
      } finally {
        saveLoading.value = false;
      }
    }
  });
};
// ==================== 查看相关 ====================
// 抽屉开关
const viewDrawer = ref(false)
const viewFormRef = ref()
const viewFileList = ref([])

// 查看表单数据
const viewForm = reactive({
  id: '',
  record_date: '',
  accounting_month: '',
  record_type: 'income',
  accounting_item: '',
  amount: '',
  handler: '',
  related_document: '',
  receipt_image_path: '',
  remarks: ''
})

// // 查看抽屉关闭前的确认
// const handleViewClose = () => {
//   viewDrawer.value = false
// }

// // 处理查看时文件选择
// const handleViewFileChange = (file, fileList) => {
//   viewFileList.value = fileList
// }

// // 处理查看时文件移除
// const handleViewFileRemove = (file, fileList) => {
//   viewFileList.value = fileList
// }

// 查看账单
const handleView = async (row) => {
  // 将选中行的数据填充到查看表单中
  Object.assign(viewForm, {
    id: row.id,
    record_date: row.record_date,
    accounting_month: row.accounting_month,
    record_type: row.record_type,
    accounting_item: row.accounting_item,
    amount: row.amount,
    handler: row.handler,
    related_document: row.related_document,
    receipt_image_path: row.receipt_image_path || '',
    remarks: row.remarks
  })

  // 如果有收据图片，获取完整地址
  if (viewForm.receipt_image_path && viewForm.receipt_image_path.trim() !== '') {
    try {
      const { data } = await getUploadFile({
        fileName: viewForm.receipt_image_path.split('/').pop(),
        dirType: 3 // 经营记账分类
      });

      if (data && data.url) {
        // 关键调整：根据后端静态资源配置拼接路径
        const staticBaseUrl = 'http://localhost:3000/static';
        let imageUrl = data.url;

        // 处理相对路径/绝对路径，确保格式统一
        if (imageUrl.includes('/public/')) {
          imageUrl = imageUrl.replace('/public/', '/static/'); // 关键修正：替换目录
        } else {
          // 若路径不含/public，直接拼接静态资源根目录
          imageUrl = `${staticBaseUrl}/${imageUrl.replace(/^\//, '')}`;
        }

        viewForm.receipt_image_path = imageUrl;

        // 更新查看界面的文件列表（与编辑界面格式一致）
        viewFileList.value = [{
          name: imageUrl.split('/').pop() || 'receipt.jpg',
          url: imageUrl, // 这里的url必须是正确的可访问路径
          status: 'success'
        }];
      }
    } catch (error) {
      console.error('获取图片地址失败:', error);
      ElMessage.error('图片加载失败');
    }
  } else {
    // 无图片时清空列表
    viewFileList.value = [];
  }
  viewDrawer.value = true;
};

// ==================== 图表相关 ====================
// 用于获取图表DOM容器
const chartRef = ref(null);
// 存储ECharts实例
let myChart = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  myChart = echarts.init(chartRef.value);

  // 基础配置（已调整标题位置、删除背景相关代码）
  const baseOption = {
    title: {
      text: '每日收入支出统计',
      left: 'left',
      right: '20px',
      top: '10px',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      },
      rich: {
        menu: {
          fontSize: 20,
          color: '#333',
          marginLeft: '10px'
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const index = params[0].dataIndex + 1;
        const income = params.find(item => item.seriesName === '收入').value;
        const expense = params.find(item => item.seriesName === '支出').value;
        const formatMoney = (num) => `¥${num.toLocaleString()}`;
        return `${index}\n收入：${formatMoney(income)}\n支出：${formatMoney(expense)}`;
      },
      backgroundColor: '#fff',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: { color: '#333' },
      padding: 10
    },
    legend: {
      data: ['收入', '支出'],
      bottom: '5%',
      left: 'center',
      itemGap: 20,
      icon: ['circle', 'diamond'],
      textStyle: { fontSize: 12 }
    },
    grid: {
      left: '3%',
      right: '3%',
      top: '20%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['8-01', '8-02', '8-03', '8-04', '8-05', '8-06', '8-07'],
      axisLine: { show: true },
      axisTick: { show: true },
      splitLine: { show: false },
      axisLabel: { fontSize: 12 }
    },
    yAxis: {
      type: 'value',
      name: '金额(円)',
      nameTextStyle: { fontSize: 12 },
      min: 12000,
      max: 20000,
      axisLine: { show: true },
      axisTick: { show: true },
      splitLine: {
        show: true,
        lineStyle: { color: '#eee' }
      },
      axisLabel: {
        formatter: (value) => `${value / 1000}k`,
        fontSize: 12
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: { color: 'green' },
        lineStyle: { width: 2 },
        data: [15800, 14200, 17000, 15000, 17500, 16000, 19000]
      },
      {
        name: '支出',
        type: 'line',
        smooth: true,
        symbol: 'diamond',
        symbolSize: 8,
        itemStyle: { color: 'red' },
        lineStyle: { width: 2 },
        data: [12500, 14600, 13800, 15000, 14800, 16000, 15500]
      }
    ]
  };

  myChart.setOption(baseOption);
};


const handleResize = () => {
  if (myChart) myChart.resize();
};

// 生命周期：挂载后初始化
onMounted(() => {
  // 使用 setTimeout 确保 DOM 完全渲染
  setTimeout(() => {
    initChart();
  }, 100);
});

// 生命周期：卸载前销毁
onUnmounted(() => {
  if (myChart) myChart.dispose();
  window.removeEventListener('resize', handleResize);
});

// 监听容器变化（仅适配图表）
watchEffect(() => {
  if (myChart) myChart.resize();
});
</script>

<style lang="less" scoped>
.card-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-drawer {
  margin-bottom: 0;
  padding: 15px;
  font-size: 20px !important;
}

.el-drawer__header {
  position: relative;
  padding: 15px;
}

.el-drawer__header .el-drawer__close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  z-index: 10;
}

.el-drawer__header .el-drawer__close-btn:hover {
  color: #666;
}

.search-filter-container {
  margin: 20px 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.drawer-title {
  font-size: 14px;
  font-weight: bold;
}

.statistics-container {
  margin: 20px 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1B82F1;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}

.positive {
  color: #67c23a;
}

.negative {
  color: #f56c6c;
}

/* 图表样式 */
.chart-container {
  margin: 20px 0;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

.legend {
  display: flex;
  gap: 20px;
  padding: 10px 0;
  font-size: 12px;
  color: #666;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-color {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.income {
  background-color: #4CAF50;
}

.expense {
  background-color: #F44336;
}

.drawer-content {
  padding: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
  position: relative;
}

.drawer-footer {
  margin-top: 30px;
  text-align: right;
  padding-right: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  position: absolute;
  bottom: 10px; // 固定在距离底部 20px 处
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 0 20px;
}

.el-upload--picture-card {
  width: 80px;
  height: 80px;
  border: 2px dashed #d9d9d9;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.el-upload--picture-card:hover {
  border-color: #409eff;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item-name {
  display: none;
}

.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item-status-label {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  font-size: 12px;
}

.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item-delete {
  position: absolute;
  top: 50%;
  right: 50%;
  transform: translate(50%, -50%);
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  font-size: 12px;
  cursor: pointer;
}

.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item-delete:hover {
  background-color: rgba(255, 0, 0, 0.6);
}

.el-upload-list--picture-card .el-upload-list__item .el-upload-list__item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.form-section-title {
  font-size: 14px;
  color: #1B82F1;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 3px solid #1B82F1;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: normal;
  color: #333;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

.preview-container {
  margin-top: 10px;
  width: 100%;
  height: 100px;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 4px;
}

.drawer-footer {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.el-button {
  padding: 8px 16px;
  font-size: 12px;
}

.el-button--primary {
  background-color: #1B82F1;
  border-color: #1B82F1;
  color: white;
}

.el-button--primary:hover {
  background-color: #1a7bc2;
  border-color: #1a7bc2;
}

.chart-container {
  width: 100%;
  height: 400px;
}
</style>